package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.RecommendUserApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.vo.PageResult;
import com.tanhua.common.vo.RecommendUserQueryParam;
import com.tanhua.common.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class TodayBestService {

    //REST请求方案的模版需要自己添加到springIOC中
    @Autowired
    private RestTemplate restTemplate;
    //获取地址
    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    /*   @Autowired
       private ErrorResult error;
   */
    @Reference(version = "1")
    private RecommendUserApi recommendUserApi;

    @Autowired
    private UserInfoService userInfoService;

    //获取今日佳人
    public TodayBest selectTodayBest() {
        //获取user
        User user = UserThreadLocal.get();
        if (user == null) return null;

        //通过dubbo远程调用RecommendUserApi查询MongoDB数据库得到与自己缘分值最高的用户信息
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(user.getId());
        if (recommendUser == null) return null;

        //通过与自己缘分值最高的用户ID查询mysql数据库得到该用户的详细信息
        UserInfo userInfo = userInfoService.selectUserInfo(recommendUser.getUserId());
        if (userInfo == null) return null;
        //对查询出来的数据进行封装
        TodayBest todayBest = new TodayBest();
        try {
            todayBest.setAge(userInfo.getAge());
            //Math.floor去掉小数点后的值, Double.valueOf().longValue()就是强转为long,这样写比较装逼!
            todayBest.setFateValue(Double.valueOf(Math.floor(recommendUser.getScore())).longValue());
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setId(userInfo.getUserId());
        } catch (Exception e) {
            return null;
        }
        return todayBest;
    }

    //获取首页推荐用户
    public PageResult selectRecommendation(RecommendUserQueryParam param) {

        //获取user
        User user = UserThreadLocal.get();
        if (user == null) return null;

        //通过dubbo远程调用RecommendUserApi查询MongoDB数据库得到与自己缘分值又高至低的用户信息
        PageInfo<RecommendUser> recommendUserPageInfo = recommendUserApi.queryPageInfo(
                user.getId(),
                param.getPage(),
                param.getPagesize());
        //判断是否为空
        if (recommendUserPageInfo.getRecords() == null) return null;
        //将推荐用户的ID与缘分值存入map中
        HashMap<Long, Double> map = new HashMap<>();
        List<RecommendUser> records = recommendUserPageInfo.getRecords();
        for (RecommendUser record : records) {
            map.put(record.getUserId(), record.getScore());
        }

        //通过条件查询用户
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", map.keySet());
        List<UserInfo> userInfos = userInfoService.selectUserInfos(queryWrapper);
        if (userInfos == null) return null;

        //数据填充
        List<TodayBest> list = new ArrayList<>();
        TodayBest todayBest;
        try {
            for (UserInfo userInfo : userInfos) {
                todayBest = new TodayBest();
                todayBest.setId(userInfo.getUserId());
                todayBest.setAvatar(userInfo.getLogo());
                todayBest.setNickname(userInfo.getNickName());
                todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
                todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
                todayBest.setAge(userInfo.getAge());
                //Math.floor去掉小数点后的值, Double.valueOf().longValue()就是强转为long,这样写比较装逼!
                todayBest.setFateValue(Double.valueOf(Math.floor(map.get(userInfo.getUserId()))).longValue());

                list.add(todayBest);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //排序   /**o1-o2为升序序排列，o2-o1为降序排列，若具体到某一字段，则根据该字段进行排列*/
        list.sort((todayBest1, todayBest2) -> new Long(
                todayBest2.getFateValue() - todayBest1.getFateValue()).intValue());

        //数据封装
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(pageResult.getPagesize());
        pageResult.setItems(list);
        if (pageResult == null) return null;
        return pageResult;
    }
}
